import * as echarts from 'echarts';
import {ref} from 'vue';
export default function () {
  const resizeFunctionAttr = ref([]);

  // 初始化图表
  const initChart = info => {
    if (!info.chart) {
      const el = document.querySelector(info.selector);
      info.chart = echarts.init(el);
    }
  };

  // 针对单个图表的异步加载
  const drawChart = async (info, option, cb) => {
    info.isLoading = true;
    initChart(info);
    const res = await info.api();
    info.isLoading = false;
    if (res.status === 200 && res.data) {
      cb(res.data);
      info.chart.setOption(option, true);
      handleResize(info.chart.resize);
      info.isEmpty = false;
    } else {
      info.isEmpty = true;
    }
  };

  // 图表随窗口缩放
  const handleResize = func => {
    const resizeCallback = () => {
      try {
        func();
      } catch (e) {}
    };
    window.addEventListener('resize', resizeCallback);
    resizeFunctionAttr.value.push(resizeCallback);
  };

  // 移除所有监听的resize方法
  const removeResizeHandler = () => {
    resizeFunctionAttr.value.map(func => window.removeEventListener('resize', func));
    resizeFunctionAttr.value = [];
  };

  // 销毁图表实例释放资源
  const disposeCharts = chartsList => {
    chartsList.map(item => {
      if (item.chart) {
        echarts.dispose(item.chart);
        item.chart = null;
      }
    });
    removeResizeHandler();
  };

  return {
    initChart,
    drawChart,
    handleResize,
    disposeCharts
  };
}
